/*
 * Copyright 2018 - YZTC
 * 
 * YZTC
 * 本公司保留所有下述内容的权利。
 * 本内容为保密信息，仅限本公司内部使用。
 * 非经本公司书面许可，任何人不得外泄或用于其他目的。
 */
package com.wxmp.core.qrcode;  
import javax.imageio.ImageIO;

import com.wxmp.core.util.QRCodeUtil;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.WritableRaster;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
public class PicHelper {
    private Font font = new Font("宋体",Font.BOLD, 28);
    private Graphics2D g = null;
    private int fontsize = 12;
    private int x = 0;
    private int y = 0;
    /**
     * 导入本地图片到缓冲区
     */
    public BufferedImage loadImageLocal(String imgName) {
        try {
            return ImageIO.read(new File(imgName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 导入网络图片到缓冲区
     */
    public BufferedImage loadImageUrl(String imgName) {
        try {
            URL url = new URL(imgName);
            return ImageIO.read(url);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 生成新图片到本地
     */
    public boolean writeImageLocal(String newImage, BufferedImage img) {
        boolean flag = false;
        if (newImage != null && img != null) {
            try {
                File outputfile = new File(newImage);
                ImageIO.write(img, "jpg", outputfile);
                flag = true;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return flag;
    }
    /**
     * 设定文字的字体等
     */
    public void setFont(String fontStyle, int fontSize) {
        this.fontsize = fontSize;
        this.font = new Font(fontStyle, Font.BOLD, fontSize);
    }
    /**
     * 修改图片,返回修改后的图片缓冲区（只输出一行文本）
     */
    public BufferedImage modifyImage(BufferedImage img, Object content, int x,
            int y) {
        try {
            int w = img.getWidth();
            int h = img.getHeight();
            g = img.createGraphics();
            g.setBackground(Color.WHITE);
            g.setColor(Color.black);//设置字体颜色
            if (this.font != null)
                g.setFont(this.font);
            if (x >= w || y >= h) {
                this.x = h - this.fontsize + 2;
                this.y = w;
            } else {
                this.x = x;
                this.y = y;
            }
            if (content != null) {
                g.drawString(content.toString(), this.x, this.y);
            }
            g.dispose();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return img;
    }
    /**
     * 修改图片,返回修改后的图片缓冲区（输出多个文本段） xory：true表示将内容在一行中输出；false表示将内容多行输出
     */
    public BufferedImage modifyImage(BufferedImage img, Object[] contentArr,
            int x, int y, boolean xory) {
        try {
            int w = img.getWidth();
            int h = img.getHeight();
            g = img.createGraphics();
            g.setBackground(Color.WHITE);
            g.setColor(Color.black);
            if (this.font != null)
                g.setFont(this.font);
            if (x >= w || y >= h) {
                this.x = w - this.fontsize + 2;
                this.y = h;
            } else {
                this.x = x;
                this.y = y;
            }
            if (contentArr != null) {
                int arrlen = contentArr.length;
                if (xory) {
                    for (int i = 0; i < arrlen; i++) {
                        g.drawString(contentArr[i].toString(), this.x, this.y);
                        this.x += contentArr[i].toString().length()
                                * this.fontsize / 2 + 5;// 重新计算文本输出位置
                    }
                } else {
                    for (int i = 0; i < arrlen; i++) {
                        g.drawString(contentArr[i].toString(), this.x, this.y);
                        this.y += this.fontsize + 2*22;// 重新计算文本输出位置
                    }
                }
            }
            g.dispose();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return img;
    }
    /**
     * 修改图片,返回修改后的图片缓冲区（只输出一行文本）
     * 
     * 时间:2007-10-8
     * 
     * @param img
     * @return
     */
    public BufferedImage modifyImageYe(BufferedImage img) {
        try {
            int w = img.getWidth();
            int h = img.getHeight();
            g = img.createGraphics();
            g.setBackground(Color.WHITE);
            g.setColor(Color.blue);//设置字体颜色
            if (this.font != null)
                g.setFont(this.font);
            g.drawString("www.hi.baidu.com?xia_mingjian", w - 85, h - 5);
            g.dispose();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return img;
    }
    public BufferedImage modifyImagetogeter(BufferedImage b, BufferedImage d,int x,int y) {
        try {
            int w = b.getWidth();
            int h = b.getHeight();
            g = d.createGraphics();
            g.drawImage(b, x, y, w, h, null);
            g.dispose();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return d;
    }
    public BufferedImage resize(BufferedImage imgsrc,int widthdist,int heightdist) {      
        try {
            BufferedImage tag= new BufferedImage((int) widthdist, (int) heightdist,BufferedImage.TYPE_INT_RGB);      
            tag.getGraphics().drawImage(imgsrc.getScaledInstance(widthdist, heightdist,  Image.SCALE_SMOOTH), 0, 0,  null);      
            return tag;
        } catch (Exception ex) {      
            ex.printStackTrace();      
        }    
        return null;
    }    
    
    /**  
     * 实现图像的等比缩放  
     * @param source  
     * @param targetW  
     * @param targetH  
     * @return  
     */  
    public static void resize(InputStream in, String outFilePath, int targetW,   
            int targetH) throws Exception {  
        BufferedImage source = ImageIO.read(in);   
        int type = source.getType();   
        BufferedImage target = null;   
        double sx = (double) targetW / source.getWidth();   
        double sy = (double) targetH / source.getHeight();   
        if (sx < sy) {   
            sx = sy;   
            targetW = (int) (sx * source.getWidth());   
        } else {   
            sy = sx;   
            targetH = (int) (sy * source.getHeight());   
        }
        if (type == BufferedImage.TYPE_CUSTOM) { // handmade   
            ColorModel cm = source.getColorModel();   
            WritableRaster raster = cm.createCompatibleWritableRaster(targetW,   
                    targetH);   
            boolean alphaPremultiplied = cm.isAlphaPremultiplied();   
            target = new BufferedImage(cm, raster, alphaPremultiplied, null);   
        } else  
            target = new BufferedImage(targetW, targetH, type);   
        Graphics2D g = target.createGraphics();   
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,   
                RenderingHints.VALUE_INTERPOLATION_BICUBIC);   
        g.drawRenderedImage(source, AffineTransform.getScaleInstance(sx, sy));   
        g.dispose();   
        ImageIO.write(target, "jpg", new File(outFilePath)); 
    }  
    public static void main(String[] args) throws Exception {
        PicHelper tt = new PicHelper();
        BufferedImage qrcode = QRCodeUtil.createImage("http://wx.zxpost.com/yztc_weixin/api/wechat/oauth2user?storeCode=100002&state=yztc&redirectUrl=http://wx.zxpost.com/yztc_weixin/open/1576_100002?api=userinfo");
        BufferedImage img = tt.modifyImage(ImageIO.read(new File("/Users/adminpc/Downloads/my.jpg")), new Object[]{"我是 郑化力","手机流量充值中心"}, 240, 1290,false); 
        img = tt.modifyImagetogeter(qrcode,img,200,720);
        BufferedImage myAv = ImageIO.read(new File("/Users/adminpc/Downloads/test.png"));
        img = tt.modifyImagetogeter(myAv,img,100,1260);
        tt.writeImageLocal("/Users/adminpc/Downloads/my4.jpg", img);
        ByteArrayOutputStream os = new ByteArrayOutputStream();  
        ImageIO.write(img, "jpg", os);  
        InputStream is = new ByteArrayInputStream(os.toByteArray()); 
        resize(is, "/Users/adminpc/Downloads/my5.jpg", 640, 960);
    }
}
